﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using RL.BizSrvc;
using System.Reflection;
	public abstract class JsonPort : PageTemplate
	{
		public bool RenderOtherHtml
		{
			get
			{
				return false;
			}
		}
		public abstract string ModelNamespace { get; }
		public virtual void ProcessAjaxRequest()
		{
			Response.Headers.Add("Content-type", "text/json");
			Response.Headers.Add("Content-type", "application/json");

			JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
			StringResponse viewResult = new StringResponse();
			object result = null;
			string model = Request["model"]; 
			string action = Request["action"]; 
			string view = Request["view"];
			string nons = Request["nons"];
			string ns = Request["ns"];

			string errorMsg = string.Empty; 
			string stackTrace = string.Empty;
			string nsuse = string.Empty;			
			Response.Clear();
			
			if (model.IsNotNullOrEmpty() && action.IsNotNullOrEmpty())
			{
				try
				{
					if (nons.IsNullOrEmpty())
					{
						nsuse = ns.IsNotNullOrEmpty() ? ns : ModelNamespace;
					}
					string modelFullName = string.Format("{0}.{1}", nsuse, model);
					
					var appCodeTypes = Assembly.Load("App_Code").GetTypes().ToList();					
					Type mType = (from t in appCodeTypes
												where t.FullName.MatchByString(modelFullName)
												select t).One();
					MethodInfo mi = mType.GetMethod(action);
					object[] parameters = new object[] { };
					result = mi.Invoke(mType, parameters);

					if (view.IsNotNullOrEmpty())
					{
						string controlMarkup = string.Empty;						
						if (null != result)
						{
							AjaxView uc = Page.LoadControl("~/" + WebAppSettings.AjaxViewFolder + "/" + view + ".ascx") as AjaxView;
							uc.SetRawModel(result);
							controlMarkup = this.RenderControlHtml(uc);
						}
						if (result is ServiceResponse)
						{
							var sr = result as ServiceResponse;
							viewResult.Status = sr.Status;
							viewResult.ValidationErrors = sr.ValidationErrors;
							viewResult.FriendlyMessage = sr.FriendlyMessage;
							viewResult.Exception = sr.Exception;
							viewResult.StringObject = controlMarkup;
							Response.Write(jss.Serialize(viewResult));
							return;
						}
						else
						{
							Response.Write(jss.Serialize(controlMarkup));
							return;
						}
					}
				}
				catch (Exception error)
				{
					Response.Write(jss.Serialize(new ServiceResponse { 
					Status = ReponseStatus.ApplicationException,						
					Exception = new Error(error.Message, error.StackTrace)
					}));
					return;
				}
			}
			else
			{
				ServiceResponse badr = ServiceResponse.SendValidationErrors(new string[] { "Bad Request" });
								Response.Write(jss.Serialize(badr));
				return;
			}
			if(result.IsNotNullOrEmpty())			Response.Write(jss.Serialize(result));
		}
	}